// component/sku/sku.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {},

  /**
   * 组件的初始数据
   */
  data: {
    skuShow: false,
    detail: '',
    datas: [],
    way: '',
    skuDisplay: '',
    skuDetail: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    numChange(e) {
      this.triggerEvent('setNum', e.detail)
    },
    skuClick(e) {
      let i = e.currentTarget.dataset.i
      let index = e.currentTarget.dataset.in
      let datas = this.data.datas
      for (let x in datas[i].value) {
        datas[i].value[x].choose = index != x ? false : true
      }
      this.setData({
        datas: datas
      })
      this.skuFind()
    },
    skuFind() {
      let datas = this.data.datas
      let skuName = ''
      let skuDisplay = ''
      for (let x in datas) {
        for (let y in datas[x].value) {
          if (datas[x].value[y].choose) {
            skuName != '' && (skuName += '-')
            skuName += datas[x].value[y].value
            skuDisplay != '' && (skuDisplay += '+')
            skuDisplay += datas[x].value[y].value
          }
        }
      }
      wx.$https('goods.sku.find', {
        skuName: skuName,
        goodsId: this.data.detail.goodsId,
      }).then(res => {
        this.setData({
          skuDetail: res == null ? '' : res,
          skuDisplay: skuDisplay
        })
        this.triggerEvent('skuChoose', skuDisplay)
      })
    },
    hideShow(step) {
      let skuShow = !this.data.skuShow
      this.setData({
        skuShow: skuShow
      })
      if (skuShow && step)
        this.selectComponent('#step').setNum(step)
    },
    init(data, way) {
      let datas = JSON.parse(data.kvJson)
      for (let x in datas) {
        datas[x].value = datas[x].values.split(',').map(v => {
          return {
            value: v,
            choose: false,
            way: way
          }
        })
      }
      this.setData({
        datas: datas,
        detail: data
      })
    },
    stopEvent() {
      // console.log(this.data)
    },
    spcardAdd(e) {
      let status = e.currentTarget.dataset.status
      let skuDetail = this.data.skuDetail
      let goodsDetail = this.data.detail
      let step = this.selectComponent('#step')
      if (skuDetail) {
        if (status == 1) {
          wx.$https('spcart.add', {
            shopId: goodsDetail.shopId,
            goodsSkuId: skuDetail.goodsSkuId,
            amount: step.data.value
          }).then(res => {
            wx.showToast({
              title: '已加入购物车',
            })
            this.hideShow()
          })
        } else if (status == 2) {
          wx.$nav('/pages/order/order', {
            skuDetail: JSON.stringify({
              ...skuDetail,
              amount: step.data.value
            }),
            // goodsDetail: JSON.stringify(goodsDetail)
          })
        }
      } else {
        wx.showToast({
          title: '请选择',
          icon: 'none'
        })
      }
    },
  }
})